package com.swy.shopgroup.view;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sl.utakephoto.compress.CompressConfig;
import com.sl.utakephoto.exception.TakeException;
import com.sl.utakephoto.manager.ITakePhotoResult;
import com.sl.utakephoto.manager.UTakePhoto;
import com.swy.shopgroup.CircleImageView;
import com.swy.shopgroup.MainActivity;
import com.swy.shopgroup.R;
import com.swy.shopgroup.Utils;
import com.swy.shopgroup.entity.ResultBean;
import com.swy.shopgroup.entity.ShopUser;
import com.swy.shopgroup.network.OkHttp;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Response;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class RegisterActivity extends AppCompatActivity {

    private CircleImageView icon;
    private File uploadFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        Utils.checkAllPer(this);
        initView();
        initData();
    }

    public void initView() {
        icon = findViewById(R.id.icon);
    }

    public void initData() {

    }

    public void click(View v) {
        switch (v.getId()) {
            case R.id.icon:
                UTakePhoto.with(this).openAlbum()
                        .setCompressConfig(new CompressConfig.Builder().create())
                        .build(new ITakePhotoResult() {
                            @Override
                            public void takeSuccess(List<Uri> uriList) {
                                Uri uri = uriList.get(0);
                                uploadFile = new File(Objects.requireNonNull(uri.getPath()));
                                Bitmap bitmap = BitmapFactory.decodeFile(uri.getPath());
                                icon.setImageBitmap(bitmap);
                            }

                            @Override
                            public void takeFailure(TakeException ex) {

                            }

                            @Override
                            public void takeCancel() {

                            }
                        });
                break;
            case R.id.register:
                register();
                break;
            case R.id.mFinish:
                Intent intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
                finish();
                break;
            default:
                break;
        }
    }

    @SuppressLint("CheckResult")
    public void register() {
        final ShopUser user = new ShopUser();
        ShopUser.DataBean bean = new ShopUser.DataBean();
        user.setData(bean);
        String name = checkInputErr(R.id.phoneNum);
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        user.getData().setName(name);
        String pwd = checkInputErr(R.id.code);
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }
        user.getData().setPassword(pwd);
        String nick = checkInputErr(R.id.nickEdit);
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "请输入昵称", Toast.LENGTH_SHORT).show();
            return;
        }
        user.getData().setNickname(nick);
        user.getData().setSex(((Spinner) findViewById(R.id.sexSelect)).getSelectedItemPosition() == 0 ? "男" : "女");
        user.getData().setType(((Spinner) findViewById(R.id.typeSelect)).getSelectedItemPosition() == 0 ? 1 : 2);
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                OkHttp o = new OkHttp();
                try {
                    Response response = o.register(uploadFile, user);
                    e.onNext(response.body().string());
                } catch (IOException a) {
                    a.printStackTrace();
                    e.onNext("s");
                }
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new io.reactivex.functions.Consumer<String>() {
            @Override
            public void accept(@io.reactivex.annotations.NonNull String s) throws Exception {
                try {
                    Gson gson = new Gson();
                    ResultBean result = gson.fromJson(s, ResultBean.class);
                    if (result.getCode().equals("200")) {
                        Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    }
                    Toast.makeText(RegisterActivity.this, result.getMsg(), Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                }
            }
        });
    }

    public String checkInputErr(int id) {
        return ((EditText) findViewById(id)).getText().toString();
    }
}